package com.shop.cloud.service.hongfu.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shop.cloud.common.mybatis.BaseService;
import com.shop.cloud.common.mybatis.MybatisDao;
import com.shop.cloud.dao.hongfu.DistributionInstallDao;
import com.shop.cloud.dao.hongfu.DistributionMsgDao;
import com.shop.cloud.dao.hongfu.GoodsOrderDao;
import com.shop.cloud.dao.hongfu.InviteHistoryDao;
import com.shop.cloud.dao.hongfu.OrderProductDetailDao;
import com.shop.cloud.domain.hongfu.Activity;
import com.shop.cloud.domain.hongfu.BalanceHistory;
import com.shop.cloud.domain.hongfu.DistributionBean;
import com.shop.cloud.domain.hongfu.DistributionInstall;
import com.shop.cloud.domain.hongfu.DistributionMsg;
import com.shop.cloud.domain.hongfu.Goods;
import com.shop.cloud.domain.hongfu.GoodsOrder;
import com.shop.cloud.domain.hongfu.GoodsProduct;
import com.shop.cloud.domain.hongfu.InviteHistory;
import com.shop.cloud.domain.hongfu.OrderProductDetail;
import com.shop.cloud.domain.hongfu.TransactionLog;
import com.shop.cloud.domain.hongfu.User;
import com.shop.cloud.service.hongfu.IActivityService;
import com.shop.cloud.service.hongfu.IBalanceHistoryService;
import com.shop.cloud.service.hongfu.IDistributionMsgService;
import com.shop.cloud.service.hongfu.IGoodsProductService;
import com.shop.cloud.service.hongfu.IGoodsService;
import com.shop.cloud.service.hongfu.IInviteHistoryService;
import com.shop.cloud.service.hongfu.ITransactionLogService;
import com.shop.cloud.service.hongfu.IUserService;
import com.shop.cloud.util.Page;

/**
 * 分销得利处理
 * @author Yan Weiwei
 */
@Transactional
@Service("distributionMsgService")
public class DistributionMsgService extends BaseService<DistributionMsg> implements IDistributionMsgService{
	
	private Logger logger = LoggerFactory.getLogger(DistributionMsgService.class);
    
    @Autowired
	private DistributionMsgDao distributionMsgDao;
    
    @Autowired
    private InviteHistoryDao inviteHistoryDao;
    
    @Autowired
    private IInviteHistoryService inviteHistoryService;
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private ITransactionLogService transactionLogService;
    
    @Autowired
    private GoodsOrderDao goodsOrderDao;
    
    @Autowired
    private IGoodsService goodsService;
    
    @Autowired
    private DistributionInstallDao distributionInstallDao;
    
    @Autowired
    private IActivityService activityService;
    
    @Autowired
    private IGoodsProductService goodsProductService;
    
    @Autowired
    private IBalanceHistoryService balanceHistoryService;
    
    @Autowired
    private OrderProductDetailDao orderProductDetailDao;

	@Override
	public MybatisDao<DistributionMsg> getEntityDao() {
		return distributionMsgDao;
	}

	/**
	 * 处理被邀请者登陆后邀请者获取积分操作
	 */
	@Override
	public void handleLoginGetCredits(String loginUserID) {
		
		if(StringUtils.isNotEmpty(loginUserID)){
			//获取邀请历史信息
			InviteHistory inviteHistory = inviteHistoryDao.getByInviteUserID(new Long(loginUserID));
			if(null == inviteHistory){
				return;
			}
			if(inviteHistory.getIsLogin() == 0){
				inviteHistory.setIsLogin(1);
				//修改登陆状态
				inviteHistoryService.update(inviteHistory);
				
				//被邀请者信息
				User fromUser = userService.get(new Long(loginUserID));
				//被邀请者登陆 邀请者获得积分奖励
				//先获取邀请者信息
				if(null != inviteHistory){
					//关联交易流水号
					String tradeNo = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ((int)((Math.random()*9+1)*100000));
					User toUser = userService.get(inviteHistory.getUserId());
					//创建分销得利对象
					DistributionMsg distributionMsg = new DistributionMsg();
					distributionMsg.setType(0);
					distributionMsg.setTradeNo(tradeNo);
					//积分数 目前是固定
					distributionMsg.setDistriNum(10f);
					distributionMsg.setToUser(toUser.getId());
					distributionMsg.setToUserName(toUser.getNickname());
					distributionMsg.setToUserLevel(toUser.getType());
					distributionMsg.setFromUser(new Long(loginUserID));
					distributionMsg.setFromUserName(fromUser.getNickname());
					distributionMsg.setCreateTime(new Timestamp(new Date().getTime()));
					distributionMsg.setRemark(fromUser.getNickname()+"成功登陆，"+toUser.getNickname()+"获取10点积分");
					//新增一条得利记录
					this.insert(distributionMsg);
					
					TransactionLog transactionLog = new TransactionLog();
					transactionLog.setType(0);
					transactionLog.setTradeNo(tradeNo);
					transactionLog.setTradeCredits(10f);
					transactionLog.setContent("注册登录成功");
					transactionLog.setCreateTime(new Timestamp(new Date().getTime()));
					transactionLog.setRemark(fromUser.getNickname()+"成功登陆，"+toUser.getNickname()+"获取10点积分");
					//新增一条交易流水记录
					transactionLogService.insert(transactionLog);
					
					int points = toUser.getPoints();
					toUser.setPoints(points + 10);
					//修改邀请者积分余额
					userService.update(toUser);
					
					BalanceHistory balanceHistory = new BalanceHistory();
					balanceHistory.setUserId(toUser.getId());
					balanceHistory.setType(10);
					balanceHistory.setCredits(10);
					balanceHistory.setOrderNo(tradeNo);
					balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
					balanceHistory.setRemark(fromUser.getNickname()+"成功登陆，"+toUser.getNickname()+"获取10点积分");
					//创建流水
					balanceHistoryService.insert(balanceHistory);
				}
			}
		}
		
	}

	/**
	 * 处理商品购买后获取分销提成
	 */
	@Override
	public void handleGoodsGetMoney(String orderNo) throws Exception {
		
		if(StringUtils.isNotEmpty(orderNo)){
			Map<String, String> map = new HashMap<String, String>();
			map.put("orderNo", orderNo);
			//获取商品订单信息
			GoodsOrder goodsOrder = goodsOrderDao.getThisByOrderNo(map);
			if(null != goodsOrder){
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("orderNo", goodsOrder.getOrderNo());
				List<OrderProductDetail> detailList = orderProductDetailDao.getThisByOrderNo(params);
				if(null != detailList && detailList.size() > 0){
					for(int i = 0; i < detailList.size(); i ++){
						Long goodsID = detailList.get(i).getGoodsId();
						Long insGoodsProductId = detailList.get(i).getGoodsProductId();
						Integer insGoodsNum = detailList.get(i).getGoodsNum();
						
						GoodsProduct insGoodsProduct = goodsProductService.get(insGoodsProductId);
						
						//商品金额
						Float thisMoney = 0f;
						Goods goods = goodsService.get(goodsID);
						if(goods.getIsSpecialPrice() == 1){
							thisMoney = goods.getSpecialPrice()*insGoodsNum;
						}else{
							thisMoney = insGoodsProduct.getPrice()*insGoodsNum;
						}
						
						//开启分销状态
						int openDistribution = goods.getOpenDistribution();
						if(openDistribution == 1){
							//商品类型 0：鸿福商品 1：旅游商品
							int isTravelGoods = goods.getIsTravelGoods();
							
							//获取分销配置
							DistributionInstall distributionInstall = distributionInstallDao.getByTypeAndID(goodsID);
							List<DistributionBean> disList = this.handleThisJSONArray(distributionInstall);
							List<User> getUserList = new ArrayList<User>();
							
							//用户ID
							Long userID = goodsOrder.getUserId();
							User user = userService.get(userID);
							//当有分销系统时处理分销得利
							if(null != disList && disList.size() > 0){
								getUserList = this.handleThisUserDis(user.getId().toString());
							}
							logger.info("***************************"+ getUserList.size() +"*************************************");
							logger.info("***************************"+ getUserList.toString() +"*************************************");
							
							//处理分销配置和用户之间的关系
							if(null != getUserList && getUserList.size() > 0){
								for(User doUser : getUserList){
									//目前类型为1：店长获取一级分销比例利益 2：业务员获取二级分销比例利益
									int userType = doUser.getType();
									for(DistributionBean doDB : disList){
										//所得金额
										BigDecimal getValue = new BigDecimal(0);
										if(userType == 1 && "一级".equals(doDB.getDesc_name())){
											//店长分销得利处理
											//分销比例参数
											String descValue = doDB.getDesc_value();
											if(StringUtils.isNotEmpty(descValue)){
												BigDecimal thisValue = new BigDecimal(descValue);
												thisValue = thisValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
												BigDecimal thisDivde = new BigDecimal(100);
												//获取百分比
												BigDecimal resultValue = thisValue.divide(thisDivde, 2, BigDecimal.ROUND_HALF_DOWN);
												getValue = new BigDecimal(thisMoney).multiply(resultValue);
												getValue = getValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
											}
											//关联交易流水号
											String tradeNo = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ((int)((Math.random()*9+1)*100000));
											//创建分销得利对象
											DistributionMsg distributionMsg = new DistributionMsg();
											distributionMsg.setType(1);
											distributionMsg.setTradeNo(tradeNo);
											distributionMsg.setDistriNum(getValue.floatValue());
											distributionMsg.setToUser(doUser.getId());
											distributionMsg.setToUserName(doUser.getNickname());
											distributionMsg.setToUserLevel(doUser.getType());
											distributionMsg.setFromUser(new Long(userID));
											distributionMsg.setFromUserName(user.getNickname());
											distributionMsg.setCreateTime(new Timestamp(new Date().getTime()));
											distributionMsg.setRemark(user.getNickname()+"购买"+ thisMoney +"元商品,"+doUser.getNickname()+"获取"+getValue+"元");
											//新增一条得利记录
											this.insert(distributionMsg);
											
											TransactionLog transactionLog = new TransactionLog();
											if(isTravelGoods == 0){
												transactionLog.setType(1);
												transactionLog.setContent("购买福乐康商品");
											}else{
												transactionLog.setType(2);
												transactionLog.setContent("购买旅游商品");
											}
											transactionLog.setTradeNo(tradeNo);
											transactionLog.setOrderNo(orderNo);
											transactionLog.setTradeAmount(getValue.floatValue());
											transactionLog.setCreateTime(new Timestamp(new Date().getTime()));
											transactionLog.setRemark(user.getNickname()+"购买"+ thisMoney +"元商品,"+doUser.getNickname()+"获取"+getValue+"元");
											//新增一条交易流水记录
											transactionLogService.insert(transactionLog);
											
											float balance = doUser.getCanWithdrawBalance();
											BigDecimal thisBalance = new BigDecimal(balance);
											thisBalance = thisBalance.add(getValue);
											thisBalance = thisBalance.setScale(2, BigDecimal.ROUND_HALF_DOWN);
											doUser.setCanWithdrawBalance(thisBalance.floatValue());
											//修改所剩余额
											userService.update(doUser);
											
											BalanceHistory balanceHistory = new BalanceHistory();
											balanceHistory.setUserId(doUser.getId());
											balanceHistory.setType(11);
											balanceHistory.setAmount(getValue.floatValue());
											balanceHistory.setOrderNo(tradeNo);
											balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
											balanceHistory.setRemark(user.getNickname()+"购买商品，"+doUser.getNickname()+"分销获取"+getValue+"元");
											//创建流水
											balanceHistoryService.insert(balanceHistory);
										}
										if(userType == 2 && "二级".equals(doDB.getDesc_name())){
											//业务员分销得利处理
											//分销比例参数
											String descValue = doDB.getDesc_value();
											if(StringUtils.isNotEmpty(descValue)){
												BigDecimal thisValue = new BigDecimal(descValue);
												thisValue = thisValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
												BigDecimal thisDivde = new BigDecimal(100);
												//获取百分比
												BigDecimal resultValue = thisValue.divide(thisDivde, 2, BigDecimal.ROUND_HALF_DOWN);
												getValue = new BigDecimal(thisMoney).multiply(resultValue);
												getValue = getValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
											}
											//关联交易流水号
											String tradeNo = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ((int)((Math.random()*9+1)*100000));
											//创建分销得利对象
											DistributionMsg distributionMsg = new DistributionMsg();
											distributionMsg.setType(1);
											distributionMsg.setTradeNo(tradeNo);
											distributionMsg.setDistriNum(getValue.floatValue());
											distributionMsg.setToUser(doUser.getId());
											distributionMsg.setToUserName(doUser.getNickname());
											distributionMsg.setToUserLevel(doUser.getType());
											distributionMsg.setFromUser(new Long(userID));
											distributionMsg.setFromUserName(user.getNickname());
											distributionMsg.setCreateTime(new Timestamp(new Date().getTime()));
											distributionMsg.setRemark(user.getNickname()+"购买"+ thisMoney +"元商品,"+doUser.getNickname()+"获取"+getValue+"元");
											//新增一条得利记录
											this.insert(distributionMsg);
											
											TransactionLog transactionLog = new TransactionLog();
											if(isTravelGoods == 0){
												transactionLog.setType(1);
												transactionLog.setContent("购买福乐康商品");
											}else{
												transactionLog.setType(2);
												transactionLog.setContent("购买旅游商品");
											}
											transactionLog.setTradeNo(tradeNo);
											transactionLog.setOrderNo(orderNo);
											transactionLog.setTradeAmount(getValue.floatValue());
											transactionLog.setCreateTime(new Timestamp(new Date().getTime()));
											transactionLog.setRemark(user.getNickname()+"购买"+ thisMoney +"元商品,"+doUser.getNickname()+"获取"+getValue+"元");
											//新增一条交易流水记录
											transactionLogService.insert(transactionLog);
											
											float balance = doUser.getCanWithdrawBalance();
											BigDecimal thisBalance = new BigDecimal(balance);
											thisBalance = thisBalance.add(getValue);
											thisBalance = thisBalance.setScale(2, BigDecimal.ROUND_HALF_DOWN);
											doUser.setCanWithdrawBalance(thisBalance.floatValue());
											//修改所剩余额
											userService.update(doUser);
											
											BalanceHistory balanceHistory = new BalanceHistory();
											balanceHistory.setUserId(doUser.getId());
											balanceHistory.setType(11);
											balanceHistory.setAmount(getValue.floatValue());
											balanceHistory.setOrderNo(tradeNo);
											balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
											balanceHistory.setRemark(user.getNickname()+"购买商品，"+doUser.getNickname()+"分销获取"+getValue+"元");
											//创建流水
											balanceHistoryService.insert(balanceHistory);
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 处理参加活动后获取分销提成
	 */
	@Override
	public void handleJoinActivity(String userID, String activityID) {
		
		if(StringUtils.isNotEmpty(activityID)){
			//获取活动详情
			Activity activity = activityService.get(new Long(activityID));
			//获取用户详情
			User user = userService.get(new Long(userID));
			if(null != activity){
				//活动报名费
				float thisMoney = activity.getPrice();
				//分销开启状态
				int distributeType = activity.getDistributeType();
				if(distributeType == 0){
					//获取分销配置
					DistributionInstall distributionInstall = distributionInstallDao.getByTypeAndUser(new Long(activityID));
					List<DistributionBean> disList = this.handleThisJSONArray(distributionInstall);
					List<User> getUserList = new ArrayList<User>();
					
					//当有分销系统时处理分销得利
					if(null != disList && disList.size() > 0){
						getUserList = this.handleThisUserDis(userID);
					}
					logger.info("***************************"+ getUserList.size() +"*************************************");
					logger.info("***************************"+ getUserList.toString() +"*************************************");
					
					//处理分销配置和用户之间的关系
					if(null != getUserList && getUserList.size() > 0){
						for(User doUser : getUserList){
							//目前类型为1：店长获取一级分销比例利益 2：业务员获取二级分销比例利益
							int userType = doUser.getType();
							for(DistributionBean doDB : disList){
								//所得金额
								BigDecimal getValue = new BigDecimal(0);
								if(userType == 1 && "一级".equals(doDB.getDesc_name())){
									//店长分销得利处理
									//分销比例参数
									String descValue = doDB.getDesc_value();
									if(StringUtils.isNotEmpty(descValue)){
										BigDecimal thisValue = new BigDecimal(descValue);
										thisValue = thisValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
										BigDecimal thisDivde = new BigDecimal(100);
										//获取百分比
										BigDecimal resultValue = thisValue.divide(thisDivde, 2, BigDecimal.ROUND_HALF_DOWN);
										getValue = new BigDecimal(thisMoney).multiply(resultValue);
										getValue = getValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
									}
									
									//关联交易流水号
									String tradeNo = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ((int)((Math.random()*9+1)*100000));
									//创建分销得利对象
									DistributionMsg distributionMsg = new DistributionMsg();
									distributionMsg.setType(1);
									distributionMsg.setTradeNo(tradeNo);
									distributionMsg.setDistriNum(getValue.floatValue());
									distributionMsg.setToUser(doUser.getId());
									distributionMsg.setToUserName(doUser.getNickname());
									distributionMsg.setToUserLevel(doUser.getType());
									distributionMsg.setFromUser(new Long(userID));
									distributionMsg.setFromUserName(user.getNickname());
									distributionMsg.setCreateTime(new Timestamp(new Date().getTime()));
									distributionMsg.setRemark(user.getNickname()+"参加活动交了"+thisMoney+"元，"+doUser.getNickname()+"获取"+getValue+"元");
									//新增一条得利记录
									this.insert(distributionMsg);
									
									TransactionLog transactionLog = new TransactionLog();
									transactionLog.setType(3);
									transactionLog.setTradeNo(tradeNo);
									transactionLog.setActivityNo(activityID);
									transactionLog.setTradeAmount(getValue.floatValue());
									transactionLog.setCreateTime(new Timestamp(new Date().getTime()));
									transactionLog.setContent("报名参加活动");
									transactionLog.setRemark(user.getNickname()+"参加活动交了"+thisMoney+"元，"+doUser.getNickname()+"获取"+getValue+"元");
									//新增一条交易流水记录
									transactionLogService.insert(transactionLog);
									
									float balance = doUser.getCanWithdrawBalance();
									BigDecimal thisBalance = new BigDecimal(balance);
									thisBalance = thisBalance.add(getValue);
									thisBalance = thisBalance.setScale(2, BigDecimal.ROUND_HALF_DOWN);
									doUser.setCanWithdrawBalance(thisBalance.floatValue());
									//修改所剩余额
									userService.update(doUser);
									
									BalanceHistory balanceHistory = new BalanceHistory();
									balanceHistory.setUserId(doUser.getId());
									balanceHistory.setType(11);
									balanceHistory.setAmount(getValue.floatValue());
									balanceHistory.setActivityId(new Long(activityID));
									balanceHistory.setOrderNo(tradeNo);
									balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
									balanceHistory.setRemark(user.getNickname()+"参加活动，"+doUser.getNickname()+"分销获取"+getValue+"元");
									//创建流水
									balanceHistoryService.insert(balanceHistory);
								}
								if(userType == 2 && "二级".equals(doDB.getDesc_name())){
									//业务员分销得利处理
									//分销比例参数
									String descValue = doDB.getDesc_value();
									if(StringUtils.isNotEmpty(descValue)){
										BigDecimal thisValue = new BigDecimal(descValue);
										thisValue = thisValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
										BigDecimal thisDivde = new BigDecimal(100);
										//获取百分比
										BigDecimal resultValue = thisValue.divide(thisDivde, 2, BigDecimal.ROUND_HALF_DOWN);
										getValue = new BigDecimal(thisMoney).multiply(resultValue);
										getValue = getValue.setScale(2, BigDecimal.ROUND_HALF_DOWN);
									}
									
									//关联交易流水号
									String tradeNo = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ((int)((Math.random()*9+1)*100000));
									//创建分销得利对象
									DistributionMsg distributionMsg = new DistributionMsg();
									distributionMsg.setType(1);
									distributionMsg.setTradeNo(tradeNo);
									distributionMsg.setDistriNum(getValue.floatValue());
									distributionMsg.setToUser(doUser.getId());
									distributionMsg.setToUserName(doUser.getNickname());
									distributionMsg.setToUserLevel(doUser.getType());
									distributionMsg.setFromUser(new Long(userID));
									distributionMsg.setFromUserName(user.getNickname());
									distributionMsg.setCreateTime(new Timestamp(new Date().getTime()));
									distributionMsg.setRemark(user.getNickname()+"参加活动交了"+thisMoney+"元，"+doUser.getNickname()+"获取"+getValue+"元");
									//新增一条得利记录
									this.insert(distributionMsg);
									
									TransactionLog transactionLog = new TransactionLog();
									transactionLog.setType(3);
									transactionLog.setTradeNo(tradeNo);
									transactionLog.setActivityNo(activityID);
									transactionLog.setTradeAmount(getValue.floatValue());
									transactionLog.setCreateTime(new Timestamp(new Date().getTime()));
									transactionLog.setContent("报名参加活动");
									transactionLog.setRemark(user.getNickname()+"参加活动交了"+thisMoney+"元，"+doUser.getNickname()+"获取"+getValue+"元");
									//新增一条交易流水记录
									transactionLogService.insert(transactionLog);
									
									float balance = doUser.getCanWithdrawBalance();
									BigDecimal thisBalance = new BigDecimal(balance);
									thisBalance = thisBalance.add(getValue);
									thisBalance = thisBalance.setScale(2, BigDecimal.ROUND_HALF_DOWN);
									doUser.setCanWithdrawBalance(thisBalance.floatValue());
									//修改所剩余额
									userService.update(doUser);
									
									BalanceHistory balanceHistory = new BalanceHistory();
									balanceHistory.setUserId(doUser.getId());
									balanceHistory.setType(11);
									balanceHistory.setAmount(getValue.floatValue());
									balanceHistory.setActivityId(new Long(activityID));
									balanceHistory.setOrderNo(tradeNo);
									balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
									balanceHistory.setRemark(user.getNickname()+"参加活动，"+doUser.getNickname()+"分销获取"+getValue+"元");
									//创建流水
									balanceHistoryService.insert(balanceHistory);
								}
							}
						}
					}
				}
			}
		}
	}
	
	/**
	 * 解析分销配置JSON串
	 * @param distributionInstall
	 * @return
	 */
	private List<DistributionBean> handleThisJSONArray(DistributionInstall distributionInstall){
		List<DistributionBean> disList = new ArrayList<DistributionBean>();
		
		if(null != distributionInstall){
			String distriSetting = distributionInstall.getDistriSetting();
			if(StringUtils.isNotEmpty(distriSetting)){
				try {
					JSONArray jsonArray = new JSONArray(distriSetting);
					//解析分销配置属性
					if(null != jsonArray && jsonArray.length() > 0){
						for(int i = 0; i < jsonArray.length(); i ++){
							JSONObject jsonObject = jsonArray.getJSONObject(i);
							if(null != jsonObject){
								DistributionBean dBean = new DistributionBean();
								dBean.setDesc_name(jsonObject.getString("desc_name"));
								dBean.setDesc_value(jsonObject.getString("desc_value"));
								disList.add(dBean);
							}
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
		return disList;
	}
	
	/**
	 * 解析当前用户的上级（不包括跟自己同级别的用户）
	 * @param userID
	 * @return
	 */
	private List<User> handleThisUserDis(String userID){
		List<User> getUserList = new ArrayList<User>();
		
		//保存购买用户上级用户ID
		List<Long> userList = new ArrayList<Long>();
		
		User user = userService.get(new Long(userID));
		while(null != user){
			Long thisUserID = user.getInviterUserId();
			user = userService.get(thisUserID);
			if(null != user){
				userList.add(thisUserID);
			}
		}
		if(null != userList && userList.size() > 0){
			for(int i = 0; i < userList.size(); i ++){
				User insUser = userService.get(userList.get(i));
				//获取购买用户的类型 1:店长  2:业务员 3:普通用户
				int userType = insUser.getType();
				if(userType != 3){
					boolean addFlag = true;
					if(null != getUserList && getUserList.size() > 0){
						for(User tmpUser : getUserList){
							if(tmpUser.getType() == userType){
								//以保存过其一个上级就不保存以前的上级
								addFlag = false;
								break;
							}
						}
					}
					if(addFlag){
						getUserList.add(insUser);
					}
				}
			}
		}
		
		return getUserList;
	}

	/**
	 * 邀请有礼分销获取情况列表
	 */
	@Override
	public Page<DistributionMsg> getPage(DistributionMsg distributionMsg) {
		
		//分页请求参数
		Map<String, Object> params = new HashMap<String, Object>();
		if(null != distributionMsg.getTransactionLog()){
			params.put("type", distributionMsg.getTransactionLog().getType());
		}
		params.put("toUser", distributionMsg.getToUser());
		params.put("toUserName", distributionMsg.getToUserName());
		params.put("toUserLevel", distributionMsg.getToUserLevel());
		params.put("fromUser", distributionMsg.getFromUser());
		params.put("fromUserName", distributionMsg.getFromUserName());
		params.put("startTime", distributionMsg.getStartTime());
		params.put("endTime", distributionMsg.getEndTime());
		params.put("status", distributionMsg.getStatus());
		params.put("orderBy", distributionMsg.getOrderBy());
		
		long count = distributionMsgDao.countMsgAndLog(params);
		int pageIndex = distributionMsg.getPageIndex_();
		int pageSize = 20;
		if(null != distributionMsg.getPageSize_()){
			pageSize = distributionMsg.getPageSize_();
		}
		
		Page<DistributionMsg> page = new Page<DistributionMsg>(pageIndex, pageSize);
		
		int limitStart = (pageIndex - 1) * pageSize;
		params.put("limitStart", limitStart);
		
		int limitEnd = pageSize;
		params.put("limitEnd", limitEnd);
		
		page.setData(distributionMsgDao.findMsgAndLog(params));
		page.setTotalCount(count);
		
		return page;
	}
    
}